package cn.lovingliu.chanma.controller;

import com.github.benmanes.caffeine.cache.Cache;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Controller
@RequestMapping("/dll")
public class DllController {

    @Autowired
    private Sid sid;

    @Autowired
    Cache<String, Object> caffeineCache;

    @ResponseBody
    @PostMapping("/createQrcode")
    public Map<String,Object> createDll(@RequestBody Map<String,String> codeData){
        Map<String,Object> result = new HashMap<>();
        String codeStr = codeData.get("data");
        String str[] = codeStr.split("\n");

        if (str.length <= 0){
            result.put("status",500);
            result.put("msg","请确定是否输入或格式是否正确");
        }
        List<String> dllNumber =  Arrays.asList(str);
        String key = sid.nextShort();
        caffeineCache.put(key,dllNumber);

        result.put("status",200);
        result.put("data",key);
        return result;
    }

    @GetMapping("/infoByKey")
    public ModelAndView infoByMainId(@RequestParam String key){
        ModelAndView modelAndView = new ModelAndView("ma");
        Object numberObject = caffeineCache.getIfPresent(key);
        if (numberObject == null){
            modelAndView.getModel().put("data", "该记录已过期或不存在 ");
            return modelAndView;
        }
        List<String> numberList = (List<String>) numberObject;
        if (numberList.size() > 0){
            String numberPwdFormat = "<span>%s</span></br>";
            StringBuffer buffer = new StringBuffer();
            for (String code:numberList) {
                buffer.append(String.format(numberPwdFormat,code));
            }
            modelAndView.getModel().put("data", buffer.toString());
            return modelAndView;
        }
        modelAndView.getModel().put("data", "该记录已过期或不存在 ");
        return modelAndView;
    }
}
